#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Maven安装器 - 修复版
功能：
1. 自动检测操作系统
2. 使用稳定版Maven
3. 提供命令行界面选择安装目录
4. 自动下载和安装Maven
5. 解决权限和兼容性问题
"""

import platform
import requests
import os
import sys
import subprocess
import zipfile
import tarfile
import shutil
import warnings
from datetime import datetime
import time

# 忽略SSL警告
warnings.filterwarnings('ignore', message='urllib3 v2 only supports OpenSSL 1.1.1+')

# 使用最新稳定的Maven版本
MAVEN_VERSION = "3.9.11"
MAVEN_DOWNLOAD_URL = f"https://dlcdn.apache.org/maven/maven-3/{MAVEN_VERSION}/binaries/apache-maven-{MAVEN_VERSION}-bin.tar.gz"
MAVEN_DOWNLOAD_URL_WIN = f"https://dlcdn.apache.org/maven/maven-3/{MAVEN_VERSION}/binaries/apache-maven-{MAVEN_VERSION}-bin.zip"

def detect_os():
    """检测操作系统信息"""
    system = platform.system().lower()
    machine = platform.machine().lower()
    
    os_info = {
        'system': system,
        'machine': machine,
        'platform': platform.platform(),
        'version': platform.version()
    }
    
    # 确定下载文件扩展名
    if system == 'windows':
        os_info['extension'] = 'zip'
        os_info['binary_name'] = 'mvn.cmd'
        os_info['download_url'] = MAVEN_DOWNLOAD_URL_WIN
    else:  # macOS/Linux
        os_info['extension'] = 'tar.gz'
        os_info['binary_name'] = 'mvn'
        os_info['download_url'] = MAVEN_DOWNLOAD_URL
    
    return os_info

def get_default_install_path(os_info):
    """获取默认安装路径（用户目录下，避免权限问题）"""
    home_dir = os.path.expanduser("~")
    
    if os_info['system'] == 'windows':
        return os.path.join(home_dir, 'Maven')
    else:  # macOS/Linux
        return os.path.join(home_dir, 'maven')

def download_file(url, filepath):
    """下载文件"""
    print(f"开始下载: {url}")
    response = requests.get(url, stream=True, timeout=30)
    response.raise_for_status()
    
    total_size = int(response.headers.get('content-length', 0))
    downloaded_size = 0
    start_time = time.time()
    
    with open(filepath, 'wb') as f:
        for chunk in response.iter_content(chunk_size=8192):
            f.write(chunk)
            downloaded_size += len(chunk)
            
            if total_size > 0:
                progress = (downloaded_size / total_size) * 100
                elapsed_time = time.time() - start_time
                
                if elapsed_time > 0:
                    speed = downloaded_size / elapsed_time / 1024  # KB/s
                    print(f"\r下载进度: {progress:.1f}% ({downloaded_size//1024//1024}MB/{total_size//1024//1024}MB) - {speed:.1f} KB/s", end='')
                else:
                    print(f"\r下载进度: {progress:.1f}% ({downloaded_size//1024//1024}MB/{total_size//1024//1024}MB)", end='')
    
    print("\n下载完成!")

def extract_file(filepath, extract_dir):
    """解压文件"""
    print("开始解压...")
    if filepath.endswith('.zip'):
        with zipfile.ZipFile(filepath, 'r') as zip_ref:
            zip_ref.extractall(extract_dir)
    elif filepath.endswith('.tar.gz'):
        with tarfile.open(filepath, 'r:gz') as tar_ref:
            tar_ref.extractall(extract_dir)
    print("解压完成!")

def install_maven(version, install_dir, os_info):
    """安装Maven"""
    try:
        print(f"开始安装Maven {version}")
        print(f"安装目录: {install_dir}")
        
        # 创建安装目录
        os.makedirs(install_dir, exist_ok=True)
        
        # 下载Maven
        download_url = os_info['download_url']
        print(f"下载URL: {download_url}")
        
        # 下载文件
        filename = f"apache-maven-{version}-bin.{os_info['extension']}"
        filepath = os.path.join(install_dir, filename)
        
        download_file(download_url, filepath)
        
        # 解压文件
        extract_file(filepath, install_dir)
        
        # 移动文件到最终位置
        extracted_dir = os.path.join(install_dir, f"apache-maven-{version}")
        final_dir = os.path.join(install_dir, "maven")
        
        if os.path.exists(final_dir):
            shutil.rmtree(final_dir)
        shutil.move(extracted_dir, final_dir)
        
        # 清理下载文件
        os.remove(filepath)
        
        print("Maven安装完成!")
        
        # 显示环境变量配置信息
        show_environment_setup(final_dir, os_info)
        
        return True
        
    except Exception as e:
        print(f"安装失败: {str(e)}")
        return False

def show_environment_setup(maven_home, os_info):
    """显示环境变量配置信息"""
    bin_path = os.path.join(maven_home, "bin")
    
    print("\nMaven安装完成!")
    print(f"\n安装路径: {maven_home}")
    print("\n请手动配置环境变量：")
    
    if os_info['system'] == 'windows':
        print(f"\nWindows:")
        print(f"set MAVEN_HOME={maven_home}")
        print(f"set PATH=%PATH%;{bin_path}")
    else:
        print(f"\nmacOS/Linux:")
        print(f"export MAVEN_HOME={maven_home}")
        print(f"export PATH=$PATH:{bin_path}")
        print(f"\n或者将以下内容添加到 ~/.bashrc 或 ~/.zshrc:")
        print(f"export MAVEN_HOME={maven_home}")
        print(f"export PATH=$PATH:{bin_path}")
    
    print("\n配置完成后，请重新打开终端并运行 'mvn --version' 验证安装。")

def main():
    print("=== Maven安装器 (修复版) ===\n")
    
    # 检测操作系统
    os_info = detect_os()
    print(f"检测到操作系统: {os_info['platform']}")
    print(f"系统架构: {os_info['machine']}\n")
    
    # 使用固定版本
    selected_version = MAVEN_VERSION
    print(f"使用稳定版本: Maven {selected_version}")
    
    # 选择安装目录
    default_path = get_default_install_path(os_info)
    install_path = default_path
    try:
        user_path = input(f"请输入安装目录 (默认: {default_path}): ").strip()
        if user_path:
            install_path = user_path
    except:
        print(f"使用默认安装路径: {default_path}")
    
    print(f"安装目录: {install_path}")
    print()
    
    # 确认安装
    confirm = "y"  # 默认确认
    try:
        confirm = input("确认开始安装? (y/N): ").strip().lower()
    except:
        print("使用默认选择: y")
    
    if confirm in ['y', 'yes'] or not confirm:
        install_maven(selected_version, install_path, os_info)
    else:
        print("安装已取消")

if __name__ == "__main__":
    main()